package com.weimai.message.gateway.util;

import lombok.extern.slf4j.Slf4j;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.NoSuchAlgorithmException;

/**
 * 描述：通用签名工具
 * Copyright (c) 2018 Choice, Inc.
 * All Right Reserved.
 * Choice Proprietary and Confidential.
 *
 * @Author geer
 * @Since 2018/10/15
 * @Version 1.0
 **/

@Slf4j
public class SignUtil {
    
    
    /**
     * 将加密后的字节数组转换成字符串
     *
     * @param b 字节数组
     * @return 字符串
     */
    private static String byteArrayToHexString(byte[] b) {
        StringBuilder hs = new StringBuilder();
        String tmpStr;
        for (int n = 0; b != null && n < b.length; n++) {
            tmpStr = Integer.toHexString(b[n] & 0XFF);
            if (tmpStr.length() == 1) {
                hs.append('0');
            }
            hs.append(tmpStr);
        }
        return hs.toString().toLowerCase();
    }
    
    /**
     * sha256_HMAC加密
     *
     * @param message 消息
     * @param secret  秘钥
     * @return 加密后字符串
     */
    public static String sha256_HMAC(String message, String secret) {
        String hash = "";
        Mac sha256_HMAC = null;
        try {
            sha256_HMAC = Mac.getInstance("HmacSHA256");
        } catch (NoSuchAlgorithmException e) {
            log.error(e.getMessage());
            e.printStackTrace();
        }
        
        SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
        try {
            if (null != secret_key) {
                sha256_HMAC.init(secret_key);
            }
            
        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
        }
        
        byte[] bytes = sha256_HMAC.doFinal(message.getBytes());
        hash = byteArrayToHexString(bytes);
        log.debug("Sign by HmacSHA256 is : " + hash);
        
        return hash;
    }
}
